package com.icecola.d6_synchronized_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private String cardId; //卡号
    private double money; //余额
    //创建锁对象
    // 加final让锁不能二次赋值
    private final Lock lk = new ReentrantLock();

    public String getCardId() {
        return cardId;
    }

    public Account() {
    }

    public Account(String cardId, double money) {
        this.cardId = cardId;
        this.money = money;
    }
    public void drawMoney(double money) {
        String name = Thread.currentThread().getName();
        lk.lock(); //加锁
        try {
            if(this.money >= money){
                System.out.println("当前余额"+this.money);
                this.money -= money;
                System.out.println(name+"取钱成功，余额:"+this.money);
            }else {
                System.out.println(name+"余额不足");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lk.unlock();
        }

    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }


}
